import { getToken } from '@/utils/auth'

// 发送聊天消息
export async function sendMessage(data, callback) {
  const response = await fetch(import.meta.env.VITE_APP_BASE_API + '/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + getToken()
    },
    body: JSON.stringify(data)
  })

  if (!response.ok) {
    throw new Error('网络请求失败');
  }

  const reader = response.body.getReader();
  const decoder = new TextDecoder();

  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    }
    const chunk = decoder.decode(value);
    callback(chunk);
  }
}